package com.example.demo.admin.sync.cas;/**
 * Created by kete on 2018-09-18.
 */

import org.apache.commons.collections.map.HashedMap;

import java.util.Map;

/**
 * 作者：kete
 * 创建时间：2018-09-18 16:21
 * 功能描述：
 * 版本：
 */
public class MonitorVehicleTracker {
    private final Map<String,MonitorModel>  locations;

    public MonitorVehicleTracker(Map<String, MonitorModel> locations) {
        this.locations = decopy(locations);
    }

    public static void main(String[] args) {
        Map<String,MonitorModel> map = new HashedMap();
        map.put("a",new MonitorModel(1,3));
        map.put("b",new MonitorModel(2,5));

        MonitorVehicleTracker locations = new MonitorVehicleTracker(map);

        TestA a = new TestA(locations);
        TestB b = new TestB(locations);

        a.start();
        b.start();

    }

    public synchronized Map<String,MonitorModel> getLocations(){
        return decopy(locations);
    }

    public synchronized  void setLocations(String str,int x,int y){
        MonitorModel monitorModel = locations.get(str);
        if(null == monitorModel)
            throw new RuntimeException("error");
        monitorModel.setX(x);
        monitorModel.setY(y);
    }


    private static Map<String, MonitorModel>  decopy(Map<String, MonitorModel> locations) {
        Map<String,MonitorModel> result = new HashedMap();
        for(Map.Entry<String,MonitorModel> entry:locations.entrySet()){
            result.put(entry.getKey(),entry.getValue());
        }
        return  result;
    }
}


 class TestA extends Thread{
     private MonitorVehicleTracker monitorVehicleTracker;

     public TestA(MonitorVehicleTracker m) {
         monitorVehicleTracker = m;
     }

     @Override
     public void run() {

         monitorVehicleTracker.setLocations("b",3,6);
         try {
             Thread.sleep(3000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
     }
 }

class TestB extends Thread{
    private MonitorVehicleTracker monitorVehicleTracker;

    public TestB(MonitorVehicleTracker m) {
        monitorVehicleTracker = m;
    }

    @Override
    public void run() {
        Map<String,MonitorModel> map = monitorVehicleTracker.getLocations();
        map.forEach((k,v)->{System.out.println(v.getX()+":"+v.getY());});
    }
}

class MonitorModel{
     private int x;
     private int y;

     public MonitorModel(int x, int y) {
         this.x = x;
         this.y = y;
     }

     public int getX() {
         return x;
     }

     public void setX(int x) {
         this.x = x;
     }

     public int getY() {
         return y;
     }

     public void setY(int y) {
         this.y = y;
     }
 }
